const axios = require('axios');
const aes = require('../utils/aesUtil');
const lz = require('../utils/lzString');
const model = require('../utils/modelUtil');
const serverListJsonData = require('../data/server/serverList.js');

//获取服务器列表-h5
const getServerListH5 = () => {
    return new Promise((resolve, reject) => {
        axios({
            method: 'POST',
            url: 'https://h5.login.fy-game.com:9898/GetServerList',
            data: aes.encrypt(lz.compressToBase64(model.userModel('GetServerList', {account: 0, channel: 1}, true, model.userData('', 0, 0, 0)))),
            headers: {"Content-Type": 'application/x-www-form-urlencoded'},
        }).then((res) => {
            let retData = res.data;
            resolve(JSON.parse(lz.decompressFromBase64(aes.decrypt(retData.MsgData))).serverObj);
        }).catch((err) => {
            reject(err);
        })
    })
}

const getServerListOfficial = () => {
    return new Promise((resolve, reject) => {
        axios({
            method: 'POST',
            url: 'http://81.69.184.133:9898/GetServerList',
            data: aes.encrypt(lz.compressToBase64(model.userModel('GetServerList', {account: 0, channel: 1}, true, model.userData('', 0, 0, 0)))),
            headers: {"Content-Type": 'application/x-www-form-urlencoded'},
        }).then((res) => {
            let retData = res.data;
            resolve(JSON.parse(lz.decompressFromBase64(aes.decrypt(retData.MsgData))).serverObj);
        }).catch((err) => {
            reject(err);
        })
    })
}

//获取服务器信息
const getServerData = async (type, serverCode) => {
    let list = {};
    let d = {};
    switch (type) {
        case 1: // h5
            try {
                list = await getServerListH5();
                d = list[serverCode];
                return {quickLoginUrl: d[1]+'/'+d[2], reqUrl: d[1]+'/'+d[3], serverName: d[5]};
            } catch (err) {
                const s = serverListJsonData.h5[serverCode];
                return {quickLoginUrl: s[1]+'/'+s[2], reqUrl: s[1]+'/'+s[3], serverName: s[5]};
            }
            break;
        case 2: // 官服
            try {
                list = await getServerListOfficial();
                d = list[serverCode];
                return {quickLoginUrl: d[1]+'/'+d[2], reqUrl: d[1]+'/'+d[3], serverName: d[5]};
            } catch (err) {
                const s = serverListJsonData.official[serverCode];
                return {quickLoginUrl: s[1]+'/'+s[2], reqUrl: s[1]+'/'+s[3], serverName: s[5]};
            }
            break;
    }
}


module.exports = {
    getServerData,
}